package com.mh.exception;

import com.alibaba.fastjson.JSON;
import com.mh.common.ResponseResult;
import com.mh.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//自定义认证异常处理,实现AuthenticationEntryPoint接口
//AuthenticationEntryPoint用于处理未认证用户访问受保护资源时的异常
@Component
public class AuthEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    //当用户未通过认证,Spring Security 会调用commence方法-->自定义返回给客户端的响应内容
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //异常状态码+信息,封装到自定义响应结果类
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "认证失败");
        //响应结果转换为JSON字符串
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }
}
